//
//  XDSelectCityTVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/23.
//  Copyright © 2017年 East. All rights reserved.
//

#import "XDSelectCityTVC.h"
#import "XDSelCityHeaderHFView.h"
#import "XDSelCityLocCityTCell.h"
#import "XDSelCityHotCityTCell.h"
#import "XDSelCityResultTVC.h"
#import <CoreLocation/CoreLocation.h>
#import "CityModel.h"

@interface XDSelectCityTVC ()<UISearchResultsUpdating, UISearchBarDelegate, CLLocationManagerDelegate, XDSelCityHotCityTCellDelegate, XDSelCityLocCityTCellDelegate>

@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) XDSelCityResultTVC *resultsTVC;

@property (strong, nonatomic) NSDictionary<NSString *, NSArray *> *cityDic; // 城市的原始数据
@property (strong, nonatomic) NSArray<NSString *> *cityKeys;                // 排序后的城市A-Z
@property (strong, nonatomic) NSArray<NSString *> *cityValues;              // 所有的城市
@property (strong, nonatomic) NSArray<NSString *> *headerTitles;            // Headers
@property (strong, nonatomic) NSArray<NSString *> *sectionTitles;           // TableView的索引
@property (strong, nonatomic) NSArray<NSString *> *hotCitys;                // 热门城市
@property (strong, nonatomic) NSArray<NSString *> *searchCitys;             // 搜索后的城市

@property (strong, nonatomic) CLLocationManager *locationManager;
@property (assign, nonatomic) BOOL locationSuc;         // 定位是否成功
@property (copy,   nonatomic) NSString *locationCity;   // 定位城市

@end

static NSString *const kHeaderViewId = @"XDSelCityHeaderHFView";
static NSString *const kLocationCityId = @"XDSelCityLocCityTCell";
static NSString *const kHotCityId = @"XDSelCityHotCityTCell";
static NSString *const kDefaultCityId = @"UITableViewCell";

@implementation XDSelectCityTVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"选择城市";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
}

- (void)initSubViews {
    UINib *headerNib = [UINib nibWithNibName:kHeaderViewId bundle:nil];
    [self.tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:kHeaderViewId];
    UINib *locationNib = [UINib nibWithNibName:kLocationCityId bundle:nil];
    [self.tableView registerNib:locationNib forCellReuseIdentifier:kLocationCityId];
    UINib *hotNib = [UINib nibWithNibName:kHotCityId bundle:nil];
    [self.tableView registerNib:hotNib forCellReuseIdentifier:kHotCityId];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kDefaultCityId];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // SeacrhController
    self.resultsTVC = [[XDSelCityResultTVC alloc] init];
    __weak typeof(self) weakSelf = self;
    self.resultsTVC.selectIndex = ^(NSInteger index) {
        [weakSelf userDidSelectCity:weakSelf.searchCitys[index]];
    };
    // we want to be the delegate for our filtered table so didSelectRowAtIndexPath is called for both tables
//    self.resultsTVC.tableView.delegate = self;
    
    UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsTVC];
    //    searchController.delegate = self;                               //设置UISearchControllerDelegate协议代理
    searchController.searchResultsUpdater = self;                   //设置UISearchResultsUpdating协议代理
    searchController.dimsBackgroundDuringPresentation = YES;        //是否添加半透明覆盖层(主要用于有新的结果显示controller，类似短信APP)
    searchController.hidesNavigationBarDuringPresentation = YES;    //是否隐藏导航栏
    searchController.searchBar.delegate = self;
    searchController.searchBar.placeholder = @"请输入城市名称";
    [searchController.searchBar sizeToFit];
    self.searchController = searchController;
    self.definesPresentationContext = YES;
    
    self.tableView.tableHeaderView = searchController.searchBar;
    
    // 请求定位
    [self getLocation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.headerTitles.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section < 2) {
        return 1;
    }
    return self.cityDic[self.headerTitles[section]].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        XDSelCityLocCityTCell *cell = [tableView dequeueReusableCellWithIdentifier:kLocationCityId forIndexPath:indexPath];
        cell.titleStr = self.locationSuc ? self.locationCity : @"  定位失败，请点击重试  ";
        cell.delegate = self;
        return cell;
    } else if (indexPath.section == 1) {
        XDSelCityHotCityTCell *cell = [tableView dequeueReusableCellWithIdentifier:kHotCityId forIndexPath:indexPath];
        cell.cityArray = self.hotCitys;
        cell.delegate = self;
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kDefaultCityId forIndexPath:indexPath];
        NSArray *array = self.cityDic[self.headerTitles[indexPath.section]];
        cell.textLabel.text = array[indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:14.0];
        cell.textLabel.textColor = [UIColor colorWithRed:(0x33 / 255.0) green:(0x33 / 255.0) blue:(0x33 / 255.0) alpha:1.0];
        return cell;
    }
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.sectionTitles;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    if ([title isEqualToString:UITableViewIndexSearch]) {
        [tableView setContentOffset:CGPointMake(0, -64.0) animated:NO];
    }

    return index - 1;
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    XDSelCityHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderViewId];
    view.titleLabel.text = self.headerTitles[section];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 38.0 + 1.0;
    } else if (indexPath.section == 1) {
        NSInteger row = self.hotCitys.count / 3 + (self.hotCitys.count % 3 ? 1 : 0) ;
        row = (row == 0) ? 1 : row;
        return (38.0 + 10.0) * (row - 1) + 38.0 + 1.0;
    }
    return 44.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 25.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section > 1) {
        NSArray *array = self.cityDic[self.headerTitles[indexPath.section]];
        [self userDidSelectCity:array[indexPath.row]];
    }
}

#pragma mark - <UISearchResultsUpdating>代理
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = searchController.searchBar.text;
    NSLog(@"输入的搜索词语是%@", searchString);
    
    // ”^[A-Za-z]+$”
    NSMutableArray *resultArray  =  [NSMutableArray array];
    if([self isZimuWithstring:searchString]) {
        //证明输入的是字母
        NSMutableArray * pinYinArray = [NSMutableArray array]; //和输入的拼音首字母相同的地区的拼音
        NSString *upperCaseString2 = searchString.uppercaseString;
        NSString *firstString = [upperCaseString2 substringToIndex:1];
        NSArray *array = [self.cityDic objectForKey:firstString];
        [array enumerateObjectsUsingBlock:^(NSString *cityName, NSUInteger idx, BOOL * _Nonnull stop) {
            CityModel *model = [[CityModel alloc] init];
            NSString *pinYin = [self Charactor:cityName getFirstCharactor:NO];
            model.name = cityName;
            model.pinYinName = pinYin;
            [pinYinArray addObject:model];
        }];
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"pinYinName BEGINSWITH[c] %@", searchString];
        NSArray *smallArray = [pinYinArray filteredArrayUsingPredicate:pred];
        [smallArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            CityModel *model = obj;
            [resultArray addObject:model.name];
        }];
    } else {
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",searchString];
        NSArray *array = [self.cityValues filteredArrayUsingPredicate:pred];
        [resultArray addObjectsFromArray:array];
    }
    
    self.searchCitys = resultArray;
    self.resultsTVC.titleArray = resultArray;
    [self.resultsTVC.tableView reloadData];
}

#pragma mark -<UISearchBarDelegate>代理
//- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
//    NSString *searchString = searchBar.text;
//    NSLog(@"输入的搜索词语是%@", searchString);
//
//    // hand over the filtered results to our search results table
//    DAUEnginResultsTVC *tableController = (DAUEnginResultsTVC *)self.searchController.searchResultsController;
//    tableController.keywords = searchString;
//    [tableController refreshNewData];
//}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    //    // 清空全局保存的数据和界面上保存的数据
    //    DAU_APP_DELEGATE.dauModel.engineSeaResult = nil;
    //    DAUEnginResultsTVC *tableController = (DAUEnginResultsTVC *)self.searchController.searchResultsController;
    //    tableController.keywords = @"";
    //    [tableController.tableView reloadData];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"定位失败：%@", error);
    self.locationSuc = NO;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = locations.lastObject;
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    // 反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error) {
            if ([placemarks count] > 0) {
                CLPlacemark *place = [placemarks firstObject];
                
                // 据网上有人说，直辖市没有locality值，需要采用省(自测时发现是有locality的值的)
                self.locationCity = place.locality.length ? place.locality : place.administrativeArea;
                self.locationSuc = YES;
                [self.tableView reloadData];    // 刷新界面
                
                NSLog(@"name,%@",place.name);                       // 位置名
                NSLog(@"thoroughfare,%@",place.thoroughfare);       // 街道
                NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
                NSLog(@"locality,%@",place.locality);               // 市(自测 直辖市也有该值，网上有人说要用省)
                NSLog(@"subLocality,%@",place.subLocality);         // 区
                NSLog(@"administrativeArea, %@", place.administrativeArea); // 省
                NSLog(@"subAdministrativeArea, %@", place.subAdministrativeArea);
                NSLog(@"country,%@",place.country);                 // 国家
                
                //                // 获取城市
                //                NSString *city = placemark.locality;
                //                if (! city) {
                //                    // 6
                //                    city = placemark.administrativeArea;
                //                }
                
            }
        } else {
            NSLog(@"error = %@", error);
            self.locationSuc = NO;
        }
    }];
    [manager stopUpdatingLocation];
}

#pragma mark - XDSelCityHotCityTCellDelegate
- (void)xDSelCityHotCityTCell:(XDSelCityHotCityTCell *)cell selectIndex:(NSInteger)index {
    [self userDidSelectCity:self.hotCitys[index]];
}

#pragma mark - XDSelCityLocCityTCellDelegate
- (void)xDSelCityLocCityTCell:(XDSelCityLocCityTCell *)cell btnTapped:(UIButton *)btn {
    if (!self.locationSuc) {
        //检查是否允许定位
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"定位服务未开启" message:@"请在系统设置中开启定位服务" preferredStyle:UIAlertControllerStyleAlert];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"暂不" style:UIAlertActionStyleCancel handler:nil]];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url];
                }
            }]];
            [self presentViewController:alertVC animated:YES completion:nil];
        } else {
            [self getLocation];
        }
    } else {
        NSLog(@"用户选择了定位城市：%@", self.locationCity);
        [self userDidSelectCity:self.locationCity];
    }
}

#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
    //    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - private methods
- (void)getLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}

- (void)userDidSelectCity:(NSString *)city {
    if (self.selectCity) {
        self.selectCity(city);
        self.selectCity = nil;
    }
    [self cancelBarBtnTapped:self.navigationItem.leftBarButtonItem];
}

- (NSString *)Charactor:(NSString *)aString getFirstCharactor:(BOOL)isGetFirst {
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pinYin = [str capitalizedString];
    //转化为大写拼音
    if(isGetFirst) {
        //获取并返回首字母
        return [pinYin substringToIndex:1];
    } else {
        return pinYin;
    }
}

- (BOOL)isZimuWithstring:(NSString *)string {
    NSString* number=@"^[A-Za-z]+$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return  [numberPre evaluateWithObject:string];
}

#pragma mark - network request
#pragma mark - getters and setters
- (NSDictionary *)cityDic {
    if (!_cityDic) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"citydict" ofType:@"plist"];
        _cityDic = [NSDictionary dictionaryWithContentsOfFile:path];
    }
    return _cityDic;
}

- (NSArray *)cityKeys {
    if (!_cityKeys) {
        NSArray<NSString *> *keysArray = [self.cityDic allKeys];
        _cityKeys = [keysArray sortedArrayUsingSelector:@selector(compare:)];
    }
    return _cityKeys;
}

- (NSArray<NSString *> *)cityValues {
    if (!_cityValues) {
        NSArray<NSArray *> *allValues = [self.cityDic allValues];
        NSMutableArray *mArray = [NSMutableArray array];
        [allValues enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [mArray addObjectsFromArray:obj];
        }];
        _cityValues = mArray;
    }
    return _cityValues;
}

- (NSArray<NSString *> *)sectionTitles {
    if (!_sectionTitles) {
        _sectionTitles = [@[UITableViewIndexSearch, @"!", @"#"] arrayByAddingObjectsFromArray:self.cityKeys];
        //        _sectionTitles = [@[@"!", @"#"] arrayByAddingObjectsFromArray:self.cityKeys];
    }
    
    return _sectionTitles;
}

- (NSArray<NSString *> *)headerTitles {
    if (!_headerTitles) {
        _headerTitles = [@[@"定位城市", @"热门城市"] arrayByAddingObjectsFromArray:self.cityKeys];
    }
    
    return _headerTitles;
}

- (NSArray<NSString *> *)hotCitys {
    if (!_hotCitys) {
        _hotCitys = @[@"全部", @"上海", @"北京", @"广州", @"深圳", @"武汉", @"西安", @"南京", @"杭州"];
    }
    return _hotCitys;
}

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyKilometer]; // 精确度 千米级别
    }
    return _locationManager;
}
@end
